package cn.doitedu.rtmk.mgmt.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class StaticCrowdSelectionService {

    public List<Integer> crowdSelect(JSONObject paramJsonObject) throws IOException {
        // 取出静态画像条件 (一个json数组)
        JSONArray staticProfileConditionArr = paramJsonObject.getJSONArray("static_profile_condition");
        /*
        	"static_profile_condition":[
	           {
	           	"tag_name":"tag01",
	           	"operator":"match",
	           	"compare_value": "咖啡"
	           },
	           {
	           	"tag_name":"tag04",
	           	"operator":">",
	           	"compare_value": "200"
	           }
	        ],
         */

        // 去 es中根据 , 规则实例 的静态画像条件参数 , 圈选人群
        // tag02>3 ,  tag04 匹配 汽车
        // es的请求客户端
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("doitedu", 9200, "http")));

        // 用于查询参数封装的对象
        SearchRequest request = new SearchRequest("doit34");

        // 构造一个查询条件组合器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 遍历 策略实例中的 每一个 静态标签条件
        for(int i=0 ; i< staticProfileConditionArr.size(); i++) {
            JSONObject jsonObject = staticProfileConditionArr.getJSONObject(i);

            String operator = jsonObject.getString("operator");
            switch (operator) {

                case ">":
                    boolQueryBuilder.must(QueryBuilders.rangeQuery(jsonObject.getString("tag_name")).gt(jsonObject.getInteger("compare_value")));
                    break;

                case ">=":
                    boolQueryBuilder.must(QueryBuilders.rangeQuery(jsonObject.getString("tag_name")).gte(jsonObject.getInteger("compare_value")));
                    break;

                case "<":
                    boolQueryBuilder.must(QueryBuilders.rangeQuery(jsonObject.getString("tag_name")).lt(jsonObject.getInteger("compare_value")));
                    break;

                case "<=":
                    boolQueryBuilder.must(QueryBuilders.rangeQuery(jsonObject.getString("tag_name")).lte(jsonObject.getInteger("compare_value")));
                    break;

                case "match":
                    boolQueryBuilder.must(QueryBuilders.matchQuery(jsonObject.getString("tag_name"),jsonObject.getString("compare_value")));
                    break;

                default:
                    break;

            }
        }

        // 将查询参数封装到请求对象中
        request.source(new SearchSourceBuilder().query(boolQueryBuilder));

        // 用客户端发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        // 取出响应结果中所有的id（就是用户的id）
        List<Integer> ids = Arrays.stream(response.getHits().getHits()).map(hit->Integer.parseInt(hit.getId())).collect(Collectors.toList());

        return ids;
    }


    public static void main(String[] args) throws IOException {


        StaticCrowdSelectionService staticCrowdSelectionService = new StaticCrowdSelectionService();

        JSONArray jsonArray = new JSONArray(2);
        /*
        	   {
	           	"tag_name":"tag01",
	           	"operator":"match",
	           	"compare_value": "咖啡"
	           },
         */
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("tag_name","tag02");
        jsonObject1.put("operator","<");
        jsonObject1.put("compare_value",30);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("tag_name","tag04");
        jsonObject2.put("operator","match");
        jsonObject2.put("compare_value","管理");


        jsonArray.add(0,jsonObject1);
        jsonArray.add(1,jsonObject2);

        JSONObject params = new JSONObject();
        params.put("static_profile_condition",jsonArray);


        List<Integer> ids = staticCrowdSelectionService.crowdSelect(params);
        System.out.println(ids);


    }

}
